package thesis.filesharing.web.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.RedirectView;

import thesis.filesharing.web.auth.AuthUtil;
import thesis.filesharing.web.auth.AuthenticationUserDetails;
import thesis.filesharing.web.auth.Roles;

@Controller
public class LoginController {
	
	@PreAuthorize("hasAnyRole('ROLE_STUDENT', 'ROLE_LECTURER', 'ROLE_ADMIN')")
	@RequestMapping(value = "/loginsuccess", method = RequestMethod.GET)
	public RedirectView LoginSuccess() {
		AuthenticationUserDetails user = (AuthenticationUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (user == null) {
			return new RedirectView("/login.html");
		} else {
			if (AuthUtil.containAuthority(user, Roles.ROLE_STUDENT)) {
				return new RedirectView("/student/index.html");
			} else if (AuthUtil.containAuthority(user, Roles.ROLE_LECTURER)) {
				return new RedirectView("/lecturer/index.html");
			} else if (AuthUtil.containAuthority(user, Roles.ROLE_ADMIN)) {
				return new RedirectView("/admin/index.html");
			} else {
				return new RedirectView("/accessDenied.html");
			}
		}
	}
	
	@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
	public String loginError(ModelMap model) {
		model.addAttribute("error", "true");
		return "login";
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
		return "login";
	}
}
